from sqlalchemy.orm import Session
from .. import models, schemas
from fastapi import HTTPException, status

def create_avatar(db: Session, avatar: schemas.AvatarCreate, user_id: str):
    """创建用户化身"""
    # 检查用户是否已有化身
    existing_avatar = db.query(models.Avatar).filter(
        models.Avatar.user_id == user_id
    ).first()
    if existing_avatar:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户已有化身"
        )
    
    # 创建新化身
    db_avatar = models.Avatar(
        **avatar.model_dump(),
        user_id=user_id,
        avatar_likes_count=0
    )
    db.add(db_avatar)
    db.commit()
    db.refresh(db_avatar)
    
    # 更新用户的avatar_id
    user = db.query(models.User).filter(models.User.id == user_id).first()
    user.avatar_id = db_avatar.id
    db.commit()
    
    return db_avatar

def get_avatar(db: Session, avatar_id: str):
    """获取化身信息"""
    return db.query(models.Avatar).filter(models.Avatar.id == avatar_id).first()

def get_user_avatar(db: Session, user_id: str):
    """获取用户的化身"""
    return db.query(models.Avatar).filter(models.Avatar.user_id == user_id).first()

def update_avatar(db: Session, avatar_id: str, avatar_data: schemas.AvatarUpdate):
    """更新化身信息"""
    db_avatar = get_avatar(db, avatar_id)
    if not db_avatar:
        raise HTTPException(status_code=404, detail="化身不存在")
    
    for field, value in avatar_data.model_dump(exclude_unset=True).items():
        setattr(db_avatar, field, value)
    
    db.commit()
    db.refresh(db_avatar)
    return db_avatar 